<template>
  <n-layout-sider
    bordered
    collapse-mode="width"
    :collapsed-width="64"
    :width="240"
    show-trigger
    style="height: 100%"
  >
    <n-space vertical>
      <!-- 搜索和添加分组操作 -->
      <n-space justify="space-between" align="center">
        <n-button
          v-if="isRootPath"
          type="primary"
          @click="handleAddRootGroup"
          style="margin-right: 12px"
        >
          <template #icon>
            <n-icon><PlusOutlined /></n-icon>
          </template>
          添加分组
        </n-button>
        <n-input
          v-model:value="groupSearch"
          placeholder="搜索分组"
          clearable
          style="flex: 1"
        />
        <n-button
          v-if="!isRootPath"
          type="primary"
          @click="handleAddSubGroup"
        >
          <template #icon>
            <n-icon><PlusOutlined /></n-icon>
          </template>
          添加子分组
        </n-button>
      </n-space>

      <!-- 分组列表 -->
      <n-menu
        :options="filteredGroupOptions"
        :default-expanded-keys="defaultExpandedKeys"
      />
    </n-space>
  </n-layout-sider>
</template>

<script lang="ts" setup>
import { ref, computed ,} from 'vue';
import { useRoute } from 'vue-router';
import { PlusOutlined, FolderOutlined } from '@vicons/antd';
import {NLayoutSider, NSpace, NInput, NButton, NMenu, NIcon,} from 'naive-ui';
import { renderIcon } from "@/utils";
import { FetchGroupList } from '@/api/analysis/device';

const groupSearch = ref('');
const filteredGroupOptions = ref<any[]>([]);
const defaultExpandedKeys = ref<string[]>([]);

const route = useRoute();
const isRootPath = computed(() => {
  return route.path.startsWith('/analysis/device') &&
    !route.params.id &&
    !route.query.groupId;
});
// 获取分组列表
const fetchGroups = async () => {
  try {
    const groupListData = await FetchGroupList();
    filteredGroupOptions.value = groupListData.map(group => ({
      label: group.name,
      key: group.id,
      icon: renderIcon(FolderOutlined),
      children: group.children?.map(child => ({
        label: child.name,
        key: child.id,
        icon: renderIcon(FolderOutlined)
      })) || []
    }));

    // 展开所有一级和二级分组
    defaultExpandedKeys.value = filteredGroupOptions.value.flatMap(group => [
      group.key, // 一级分组key
      ...(group.children?.map(child => child.key) || []) // 二级分组keys
    ]);

  } catch (error) {
    console.error("获取分组列表失败", error);
  }
};

const handleAddSubGroup = () => {
  const currentGroupId = typeof route.params.id === 'string'
    ? route.params.id
    : Array.isArray(route.params.id)
      ? route.params.id[0]
      : '';

  const queryGroupId = typeof route.query.groupId === 'string'
    ? route.query.groupId
    : Array.isArray(route.query.groupId)
      ? route.query.groupId[0]
      : '';

  const effectiveGroupId = currentGroupId || queryGroupId;
  if (!effectiveGroupId) return;

  const newSubGroup = {
    label: `未命名${Math.floor(Math.random() * 1000)}`,
    key: `subgroup-${Date.now()}`,
    icon: renderIcon(FolderOutlined)
  };

  // 更新分组列表，添加新子分组
  filteredGroupOptions.value = filteredGroupOptions.value.map(group => {
    if (group.key === effectiveGroupId) {
      return {
        ...group,
        children: [...(group.children || []), newSubGroup]
      };
    }
    return group;
  });

  // 确保当前分组保持展开状态
  if (!defaultExpandedKeys.value.includes(effectiveGroupId)) {
    defaultExpandedKeys.value = [...defaultExpandedKeys.value, effectiveGroupId];
  }
};

// 初始化时获取分组列表
fetchGroups();
</script>
